<template>
    <el-select v-model="form[option.prop]" v-bind="option.element" @change="itemChange">
        <el-option v-for="item in list" :key="item.value" :value="item.value" :label="item.label"></el-option>
    </el-select>
</template>
<script setup lang="ts">
import { Ref, ref } from 'vue';

defineOptions({ name: 'XklSelect' })
const props = defineProps(['form', 'option'])
const emit = defineEmits(['loaded', 'itemChange', 'update:label'])
const { form, option } = props

const list: Ref<any[]> = ref([])

list.value = option.config.list

emit('loaded', list.value, (vals) => {
    list.value = vals
})



const itemChange = (val) => {
    if (Array.isArray(val)) {
        const values = val
        const items = list.value.filter(res => values.includes(res.value))
        const labels = items.map(res => res.label)
        if (items) {
            emit('update:label', labels)
            emit('itemChange', items)
        }
    } else {
        const item = list.value.find(res => res.value === val)
        if (item) {
            emit('update:label', item.label)
            emit('itemChange', item)
        }
    }
}
</script>